package top.forforever.srb.core.controller.api;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.forforever.srb.common.exception.Assert;
import top.forforever.srb.common.result.R;
import top.forforever.srb.common.result.ResponseEnum;
import top.forforever.srb.common.util.RegexValidateUtils;
import top.forforever.srb.core.pojo.entity.UserInfo;
import top.forforever.srb.core.pojo.vo.LoginVO;
import top.forforever.srb.core.pojo.vo.RegisterVO;
import top.forforever.srb.core.pojo.vo.UserIndexVO;
import top.forforever.srb.core.pojo.vo.UserInfoVO;
import top.forforever.srb.core.service.UserInfoService;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 用户基本信息 前端控制器
 * </p>
 *
 * @author Mr.Jiang
 * @since 2023-04-29
 */
@RestController
@RequestMapping("/api/core/userInfo")
public class ApiUserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("getUserIndex")
    public R getUserIndex(HttpServletRequest request) {
        String userId = request.getHeader("userId");
        UserIndexVO userIndexVO = userInfoService.getUserIndex(userId);
        return R.ok().data("userIndexVO",userIndexVO);
    }

    @GetMapping("isMobileExist/{mobile}")
    public Boolean isMobileExist(@PathVariable String mobile) {
        int count = userInfoService.count(
                new LambdaQueryWrapper<UserInfo>()
                        .eq(UserInfo::getMobile, mobile)
        );
        return count > 0;
    }

    @PostMapping("login")
    public R login(@RequestBody LoginVO loginVO, HttpServletRequest request) {
        //获取用户ip地址
        String ip = request.getRemoteAddr(); //nginx的ip地址
//        String ip = request.getHeader("X-forwarded-for"); //nginx配置代理， 获取真正本机的ip地址

        //判断注册信息
        Assert.notNull(loginVO.getUserType(),ResponseEnum.USER_TYPE_NOT_EMPTY);
        Assert.notNull(loginVO.getMobile(),ResponseEnum.MOBILE_NULL_ERROR);
        Assert.notNull(loginVO.getPassword(),ResponseEnum.PASSWORD_NULL_ERROR);
        Assert.isTrue(RegexValidateUtils.checkCellphone(loginVO.getMobile()), ResponseEnum.MOBILE_ERROR);

        UserInfoVO userInfoVO = userInfoService.login(loginVO, ip);
        return R.ok().data("userInfoVO",userInfoVO);
    }

    @PostMapping("register")
    public R register(@RequestBody RegisterVO registerVO) {
        //判断注册信息
        Assert.notNull(registerVO.getMobile(),ResponseEnum.MOBILE_NULL_ERROR);
        Assert.notNull(registerVO.getCode(),ResponseEnum.CODE_NULL_ERROR);
        Assert.notNull(registerVO.getPassword(),ResponseEnum.PASSWORD_NULL_ERROR);
        Assert.isTrue(RegexValidateUtils.checkCellphone(registerVO.getMobile()), ResponseEnum.MOBILE_ERROR);

        userInfoService.register(registerVO);
        return R.ok();
    }

}

